package net.trade.service.trade;

import java.io.InputStreamReader;
import java.security.InvalidKeyException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import net.trade.common.encrypt.rijndael.Rijndael_Util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Before;
import org.junit.Test;

public class HttpTradeTest {

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testSendPostRequest() {
		String path = "http://tradeweb.tjpme.com/tradeweb/httpXmlServlet";
		String enc = "UTF-8";
		// String params =
		// "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"1.1\"><REQ id=\"08915a38-9b84-4dc7-b7e6-b8599f82ea75\" name=\"firm_info\"><A_N></A_N><P_P></P_P><SESSION_ID>145050275750660530</SESSION_ID><USER_ID>155000000522406</USER_ID></REQ></TPME>";
		String params = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"\"><REQ id=\"0527d152-5f30-4548-b301-3db4ef6f0c78\" name=\"get_version\" /></TPME>";
		try {
			HttpTrade.sendPostRequest(path, params, enc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testSendPostRequestget_version() {
		String path = "https://tradeweb.tjpme.com/tradeweb/httpXmlServlet";
		String enc = "UTF-8";
		// String params =
		// "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"1.1\"><REQ id=\"08915a38-9b84-4dc7-b7e6-b8599f82ea75\" name=\"firm_info\"><A_N></A_N><P_P></P_P><SESSION_ID>145050275750660530</SESSION_ID><USER_ID>155000000522406</USER_ID></REQ></TPME>";
		//String params = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"1.1\"><REQ id=\"bbe738dc-4bf3-4acc-8e8d-b17e88e28d4c\" name=\"logon\"><CLT_TOKEN>cChM5iP7+40syqOvDSXhzHR1XjrsINPFUQdaswcwQ3M=</CLT_TOKEN><CLT_ZID></CLT_ZID><LOGONTIME>1383436623937</LOGONTIME><PASSWORD></PASSWORD><REGISTER_WORD></REGISTER_WORD><USER_ID>155000000522406</USER_ID><VALID_CODE>9722</VALID_CODE><VALID_UUID>7c908544-20f9-4f2b-af1d-e8c9f5f7de67</VALID_UUID><VERSIONINFO>2.6.130807.1</VERSIONINFO></REQ></TPME>";
		//String params="<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"\"><REQ id=\"0527d152-5f30-4548-b301-3db4ef6f0c78\" name=\"get_version\" /></TPME>";
		String params = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TPME version=\"1.1\"><REQ id=\"168ca6b5-fcd8-462c-894d-8b58d9bb52ad\" name=\"my_order_query\"><A_N></A_N><BUY_SELL></BUY_SELL><COMMODITY_ID></COMMODITY_ID><ISDESC>0</ISDESC><MARKET_ID /><OR_OC /><OR_ST /><OR_TP /><ORDER_NO>0</ORDER_NO><P_P></P_P><RECCNT>0</RECCNT><SESSION_ID>145331796302940043</SESSION_ID><SORTFLD></SORTFLD><STARTNUM>0</STARTNUM><USER_ID>155000000522406</USER_ID><UT>-1</UT></REQ></TPME>";
		try {
			// HttpTrade.sendPostRequest(path, params, enc);
			HttpPost httpPost = new HttpPost(path);
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(path);
			StringEntity myEntity = new StringEntity(params, "UTF-8");
			httppost.addHeader("Content-Type", "text/xml");
			httppost.setEntity(myEntity);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();
			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "UTF-8");
			char[] buff = new char[1024];
			int length = 0;
			while ((length = reader.read(buff)) != -1) {
				System.out.println(new String(buff, 0, length));
			}
			httpclient.getConnectionManager().shutdown();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Test
	public void test2(){
		String strKey = "155000000522406a";
		String cipherText="cChM5iP7+40syqOvDSXhzHR1XjrsINPFUQdaswcwQ3M=";
		int BLOCK_SIZE =24;
		try {
			System.out.println(Rijndael_Util.decode(strKey, cipherText,
					BLOCK_SIZE));
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void test1(){
		String userId="155000000522406";
		String pwd ="abc123";
		String time ="1383436623937";
		String s= userId.length()+userId+time;
		String d = "cChM5iP7+40syqOvDSXhzHR1XjrsINPFUQdaswcwQ3M=";
		try {
			String r = Decrypt(d,userId+pwd);
			System.out.println(r);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec("0102030405060708"
                    .getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = hex2byte(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
	
	public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; i++) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
                    16);
        }
        return b;
    }
 
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

}
